package top.chaileilei.zookeeper.curator;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.*;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;

/**
 * @Description 监听
 * @Time 2019/2/12
 * @Author CHAILEILEI
 * @Weblog www.chaileilei.top
 */
public class NodeCacheDemo {
    private static CuratorFramework client = CuratorFrameworkFactory.builder()
            .connectString("119.27.189.174:2181")
            .sessionTimeoutMs(5000)
            .retryPolicy(new ExponentialBackoffRetry(1000, 3))
            .build();

    private static NodeCache cache;
    private static PathChildrenCache pathChildrenCache;

    public static void main(String[] args) throws Exception {
        pathChildren();
    }

    /**
     * @Description 监听zookeeper数据节点本身的变化
     * @Param
     * @Return void
     * @Author CHAILEILEI
     * @Time 2019/2/12
     * @Blogs www.chaileilei.top
     */
    public static void nodeCache() throws Exception {
        String path = "/dfgdfg";
        client.start();
        client.create()
                .creatingParentsIfNeeded()
                .withMode(CreateMode.EPHEMERAL)
                .forPath(path, "init".getBytes());
        //client-客户端实例，path-数据节点的节点路径，dataIsCompressed-是否进行数据压缩
        cache = new NodeCache(client, path, false);
        //true-第一次启动时，立刻读取节点数据，保存
        cache.start(true);
        cache.getListenable().addListener(new NodeCacheListener() {
            @Override
            public void nodeChanged() throws Exception {
                System.out.println("Node data update, new data: " +
                        new String(cache.getCurrentData().getData()));
            }
        });
        client.setData().forPath(path, "u".getBytes());
        Thread.sleep(1000);
        client.delete().deletingChildrenIfNeeded().forPath(path);
    }

    /**
     * @Description 监听指定数据节点的子节点变化
     * @Param
     * @Return void
     * @Author CHAILEILEI
     * @Time 2019/2/12
     * @Blogs www.chaileilei.top
     */
    public static void pathChildren() throws Exception {
        String path = "/dgfgdsf";
        client.start();
        //client-客户端实例，path-数据节点路径，dataIsCompressed-是否进行数据压缩，
        // cacheData-是否缓存内容，true表示节点列表更新是，获取到节点数据内容false则不能
        //threadFactory/executorService-可以传入专门线程池，处理事件通知
        pathChildrenCache = new PathChildrenCache(client,path,true);
        pathChildrenCache.start(PathChildrenCache.StartMode.POST_INITIALIZED_EVENT);
        pathChildrenCache.getListenable().addListener(new PathChildrenCacheListener() {
            @Override
            public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
                switch (event.getType()) {
                    case CHILD_ADDED:
                        System.out.println("CHILD_ADDED," + event.getData().getPath());
                        break;
                    case CHILD_UPDATED:
                        System.out.println("CHILD_UPDATED," + event.getData().getPath());
                        break;
                    case CHILD_REMOVED:
                        System.out.println("CHILD_REMOVED," + event.getData().getPath());
                        break;
                    default:
                        break;
                }
            }
        });
        client.create().withMode(CreateMode.PERSISTENT).forPath(path);
        Thread.sleep( 1000 );
        client.create().withMode(CreateMode.PERSISTENT).forPath(path+"/c1");
        Thread.sleep( 1000 );
        client.delete().forPath(path+"/c1");
        Thread.sleep( 1000 );
        client.delete().forPath(path);



    }


}
